package com.sdehua.wear.service.impl;

import com.sdehua.wear.entity.User;
import com.sdehua.wear.dao.UserDao;
import com.sdehua.wear.service.UserService;
import lombok.extern.log4j.Log4j2;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (User)表服务实现类
 *
 * @author makejava
 * @since 2021-12-31 15:30:06
 */
@Service("userService")
@Log4j2
public class UserServiceImpl implements UserService {
    @Resource
    private UserDao userDao;

    /**
     * @MethodName login
     * @Author coffee
     * @Description 登录
     * @Date 12:57 2022/1/1
     * @Param [user]
     * @return com.sdehua.wear.entity.User
     **/
    @Override
    public User login(Map<String, Map<String,String>> user) {
        log.info("==========LOGIN=========");
        if (user.isEmpty()) return null;
        Map<String, String> map = user.get("user");
        if (map.isEmpty()) return null;
        String username = map.get("username");
        String password = map.get("password");
        if (username.isEmpty() || password.isEmpty()) return null;
        User pojo = new User();
        pojo.setUsername(username);
        pojo.setPassword(password);
        // 访问数据库
        List<User> users = userDao.queryAll(pojo);
        if (users.size() != 1) return null;
        User userDB = users.get(0);
        userDB.setPassword(null);
        return userDB;
    }

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public User queryById(Integer id) {
        return this.userDao.queryById(id);
    }

    /**
     * 查询多条数据
     *
     * @param offset 查询起始位置
     * @param limit 查询条数
     * @return 对象列表
     */
    @Override
    public List<User> queryAllByLimit(int offset, int limit) {
        return this.userDao.queryAllByLimit(offset, limit);
    }

    /**
     * 新增数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User insert(User user) {
        this.userDao.insert(user);
        return user;
    }

    /**
     * 修改数据
     *
     * @param user 实例对象
     * @return 实例对象
     */
    @Override
    public User update(User user) {
        this.userDao.update(user);
        return this.queryById(user.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.userDao.deleteById(id) > 0;
    }
}